const LhzxHttpClient = require('./LhzxHttpClient');
const { currentConfig } = require('./config_test');

/**
 * 真实短信发送测试
 * 使用配置文件中的测试参数进行实际短信发送测试
 */

async function testRealSMS() {
    console.log('=== 云翼信真实短信发送测试 ===\n');
    
    const smsClient = new LhzxHttpClient();
    const config = currentConfig.yunyx;
    
    // 检查配置是否完整
    if (!config.siid || config.siid.includes('HERE') || 
        !config.user || config.user.includes('HERE') ||
        !config.secretKey || config.secretKey.includes('HERE')) {
        console.error('❌ 测试参数未配置！');
        console.log('请先在 config_test.js 中配置以下参数：');
        console.log('- siid: 客户编号');
        console.log('- user: HTTP账号');
        console.log('- secretKey: 接口密钥');
        console.log('- testMobile: 测试手机号');
        return;
    }
    
    console.log('🔧 使用的配置参数:');
    console.log('环境:', currentConfig.environment);
    console.log('siid:', config.siid);
    console.log('user:', config.user);
    console.log('API地址:', config.apiUrl);
    console.log('测试手机号:', config.testMobile);
    console.log('扩展码:', config.extcode);
    console.log();
    
    // 测试用例1：基本短信发送
    await testBasicSMS(smsClient, config);
    
    // 测试用例2：验证码短信
    await testVerificationCodeSMS(smsClient, config);
    
    // 测试用例3：通知类短信
    await testNotificationSMS(smsClient, config);
}

// 基本短信发送测试
async function testBasicSMS(client, config) {
    console.log('📤 测试1: 基本短信发送');
    console.log('-------------------');
    
    const testMessage = `${config.signature}这是一条测试短信，时间：${new Date().toLocaleString()}`;
    
    const smsConfig = {
        siid: config.siid,
        user: config.user,
        secretKey: config.secretKey,
        mobile: config.testMobile,
        content: testMessage,
        extcode: config.extcode,
        url: config.apiUrl
    };
    
    try {
        console.log('发送内容:', testMessage);
        console.log('目标手机:', config.testMobile);
        console.log();
        
        const result = await client.sendSMS(smsConfig);
        
        console.log('📋 发送结果:');
        console.log('事务号:', result.transactionID);
        console.log('返回码:', result.retCode);
        console.log('返回消息:', result.retMsg);
        
        if (result.retCode === '0000') {
            console.log('✅ 基本短信发送成功！');
        } else {
            console.log('❌ 基本短信发送失败');
            console.log('错误详情:', result.retMsg);
        }
        
    } catch (error) {
        console.error('❌ 基本短信发送异常:', error.message);
        analyzeError(error);
    }
    
    console.log('\n' + '='.repeat(50) + '\n');
}

// 验证码短信测试
async function testVerificationCodeSMS(client, config) {
    console.log('🔐 测试2: 验证码短信发送');
    console.log('---------------------');
    
    // 生成6位随机验证码
    const verifyCode = Math.floor(100000 + Math.random() * 900000);
    const testMessage = `${config.signature}您的验证码是：${verifyCode}，请在5分钟内使用。如非本人操作，请忽略此短信。`;
    
    const smsConfig = {
        siid: config.siid,
        user: config.user,
        secretKey: config.secretKey,
        mobile: config.testMobile,
        content: testMessage,
        extcode: config.extcode,
        url: config.apiUrl
    };
    
    try {
        console.log('验证码:', verifyCode);
        console.log('发送内容:', testMessage);
        console.log('目标手机:', config.testMobile);
        console.log();
        
        const result = await client.sendSMS(smsConfig);
        
        console.log('📋 发送结果:');
        console.log('事务号:', result.transactionID);
        console.log('返回码:', result.retCode);
        console.log('返回消息:', result.retMsg);
        
        if (result.retCode === '0000') {
            console.log('✅ 验证码短信发送成功！');
            console.log('💡 请查看手机短信，验证码为:', verifyCode);
        } else {
            console.log('❌ 验证码短信发送失败');
            console.log('错误详情:', result.retMsg);
        }
        
    } catch (error) {
        console.error('❌ 验证码短信发送异常:', error.message);
        analyzeError(error);
    }
    
    console.log('\n' + '='.repeat(50) + '\n');
}

// 通知类短信测试
async function testNotificationSMS(client, config) {
    console.log('📢 测试3: 通知类短信发送');
    console.log('---------------------');
    
    const testMessage = `${config.signature}您的订单已提交成功，订单号：TEST${Date.now()}，我们将尽快为您处理。感谢您的信任！`;
    
    const smsConfig = {
        siid: config.siid,
        user: config.user,
        secretKey: config.secretKey,
        mobile: config.testMobile,
        content: testMessage,
        extcode: config.extcode,
        url: config.apiUrl
    };
    
    try {
        console.log('发送内容:', testMessage);
        console.log('目标手机:', config.testMobile);
        console.log();
        
        const result = await client.sendSMS(smsConfig);
        
        console.log('📋 发送结果:');
        console.log('事务号:', result.transactionID);
        console.log('返回码:', result.retCode);
        console.log('返回消息:', result.retMsg);
        
        if (result.retCode === '0000') {
            console.log('✅ 通知短信发送成功！');
        } else {
            console.log('❌ 通知短信发送失败');
            console.log('错误详情:', result.retMsg);
        }
        
    } catch (error) {
        console.error('❌ 通知短信发送异常:', error.message);
        analyzeError(error);
    }
    
    console.log('\n' + '='.repeat(50) + '\n');
}

// 错误分析
function analyzeError(error) {
    console.log('\n🔍 错误分析:');
    
    if (error.message.includes('ENOTFOUND')) {
        console.log('- 网络错误：无法解析域名');
        console.log('- 建议：检查网络连接和DNS设置');
    } else if (error.message.includes('ECONNREFUSED')) {
        console.log('- 连接被拒绝：服务器无法连接');
        console.log('- 建议：检查服务器地址和端口');
    } else if (error.message.includes('timeout')) {
        console.log('- 请求超时：服务器响应时间过长');
        console.log('- 建议：检查网络延迟，稍后重试');
    } else if (error.message.includes('certificate')) {
        console.log('- SSL证书错误：证书验证失败');
        console.log('- 建议：检查服务器证书或联系技术支持');
    } else {
        console.log('- 其他错误：', error.message);
        console.log('- 建议：联系技术支持');
    }
}

// 快速测试函数 - 只发送一条验证码
async function quickTest() {
    console.log('=== 快速验证码测试 ===\n');
    
    const smsClient = new LhzxHttpClient();
    const config = currentConfig.yunyx;
    
    if (!config.siid || config.siid.includes('HERE')) {
        console.error('❌ 请先配置测试参数！');
        return;
    }
    
    const verifyCode = Math.floor(100000 + Math.random() * 900000);
    const message = `${config.signature}验证码：${verifyCode}，5分钟内有效。`;
    
    const smsConfig = {
        siid: config.siid,
        user: config.user,
        secretKey: config.secretKey,
        mobile: config.testMobile,
        content: message,
        extcode: config.extcode,
        url: config.apiUrl
    };
    
    try {
        console.log('📱 发送验证码:', verifyCode);
        console.log('📧 目标手机:', config.testMobile);
        
        const result = await smsClient.sendSMS(smsConfig);
        
        if (result.retCode === '0000') {
            console.log('✅ 发送成功！请查看手机短信');
        } else {
            console.log('❌ 发送失败:', result.retMsg);
        }
        
    } catch (error) {
        console.error('❌ 发送异常:', error.message);
    }
}

// 主函数
async function main() {
    console.log('云翼信短信接口测试工具\n');
    
    // 检查命令行参数
    const args = process.argv.slice(2);
    
    if (args.includes('--quick') || args.includes('-q')) {
        await quickTest();
    } else {
        await testRealSMS();
    }
    
    console.log('测试完成！');
    console.log('\n使用说明:');
    console.log('- 完整测试: node test_real_sms.js');
    console.log('- 快速测试: node test_real_sms.js --quick');
}

// 运行测试
if (require.main === module) {
    main().catch(console.error);
}

module.exports = {
    testRealSMS,
    quickTest
}; 